import React, { useEffect } from 'react';
import { connect, Dispatch } from 'umi';
import { Form, Row, Col, Input, Button, Cascader } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { CQ_ADD_INIT, CQ_ADD_BASE } from '@/actions/cq';
import ASelect from '@/components/SelfComp/ASelect';
import { ConnectState } from '@/models/connect';
import { AppItem } from '@/types/app';
import { CqBaseInfoItem, AddCqBaseForm } from '@/types/cq';
import { DataItem } from '@/types/global';
import { getCurrentLoginUser } from '@/utils/authority';
import { formLayout, basicFormItemLayout, basicFormItemLangLayout, CascaderOption, 
  generateCascaderOptions } from '@/utils/commons';

interface CqAddProps {
  dispatch: Dispatch;
  addLoading: boolean;
  auditorData: DataItem[];
  systemData: DataItem[];
  clusterData: DataItem[];
  appList: AppItem[];
}

const FormItem = Form.Item;

/**
 * 录入需求基本信息
 */
const CqAdd: React.FC<CqAddProps> = (props) => {

  // const formRef = React.createRef<FormInstance>();
  const [form] = Form.useForm<AddCqBaseForm>();

  useEffect(() => {
    console.info('CqAdd.useEffect');
    // 查询本页面需所有参数
    // 获取所属系统
    // 获取审核人列表
    const { dispatch } = props;
    dispatch(CQ_ADD_INIT({}));
  }, []);

  const handleSubmit = async () => {
    // console.log(formRef);
    form.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const { system, ...res } = fieldsValue;
      const [ systemCode, clstCode, appCode ] = system;
      const values: CqBaseInfoItem = {
        ...res,
        systemCode,
        clstCode,
        appCode
      };
      console.log('Received values of form: ', values);
      addCqBaseInfo(values);
    }).catch();
  };

  const addCqBaseInfo = async (record: CqBaseInfoItem) => {
    // 与服务端通讯
    const { dispatch } = props;
    // 获取当前登录用户，作为录入人员
    const userCode = getCurrentLoginUser();
    const res = await dispatch(CQ_ADD_BASE({
      ...record,
      recorder: userCode
    }));
    if (res) {
      // 新增成功，则重置表单
      form.resetFields();
    }
  }

  const handleReset = () => {
    // 先清除form表单
    form.resetFields();
  }

  const { addLoading, auditorData, systemData, clusterData, appList } = props;
  const colon = false;
  // 8-8布局
  const formItemLayout = basicFormItemLayout;
  // 8-16布局
  const formItemLangLayout = basicFormItemLangLayout;
  const options: CascaderOption[] = generateCascaderOptions(appList, systemData, clusterData);

  return (
    <PageContainer>
      <ProCard title='需求基本信息'>
        <Form layout={formLayout} form={form} onFinish={handleSubmit}>
          <Row>
            <Col span={12}>
              <FormItem label="需求编号" name='cqCode' {...formItemLayout} colon={colon}
                rules={[
                  { required: true, message: '需求编号必输' },
                  /**
                  { pattern: new RegExp(/^[A-Za-z][A-Za-z0-9]{16,16}$/, "g"), message: '需求编号只能以字母开头，16位的A-Za-z0-9组成' }
                  */
                ]}>
                <Input placeholder='必须为16位长度，只包含A-Za-z0-9'/>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem label="需求名称" name='cqName' {...formItemLangLayout} colon={colon}
                rules={[
                  { required: true, message: '需求名称必输' }
                ]}>
                <Input />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem label="所属系统应用" name='system' {...formItemLangLayout} colon={colon}
                rules={[
                  { required: true, message: '所属系统应用必输' },
                ]}>
                <Cascader options={options} />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <FormItem label="审核人(主开)" name='auditor' {...formItemLayout} colon={colon}
                rules={[
                  { required: true, message: '审核人(主开)必输' },
                ]}>
                <ASelect dataSource={auditorData} />
              </FormItem>
            </Col>
          </Row>
          <Row justify='center'>
            <Col>
              <FormItem>
                <Button type="primary" loading={addLoading} htmlType="submit">
                  提交
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </ProCard>
    </PageContainer>
  );
}

export default connect((state: ConnectState) => ({
  systemData: state.systems.systemData,
  clusterData: state.systems.clusterData,
  appList: state.cqs.appList,
  auditorData: state.users.auditorData,
  addLoading: state.loading.effects['cqs/addCqBaseInfo'],
}))(CqAdd);